package fr.tm.ima.client.gxt.grid.controller;

/**
 * @author aquinault
 */

import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.command.SimpleCommand;

import com.extjs.gxt.ui.client.data.BaseListLoader;
import com.extjs.gxt.ui.client.data.HttpProxy;
import com.extjs.gxt.ui.client.data.LoadEvent;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.data.XmlReader;
import com.extjs.gxt.ui.client.event.LoadListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.google.gwt.http.client.RequestBuilder;

import fr.tm.ima.client.gxt.grid.model.ModelDataProxy;

/**
 * fill the model.
 */
public class FillModelCommand extends SimpleCommand {

	/**
	 * {@inheritDoc}
	 */
	@Override
	public final void execute(final INotification notification) {
		
	    final ModelType type = new ModelType();
	    type.root = "records";
	    type.recordName = "record";
	    type.addField("Sender", "Name");
	    type.addField("Email");
	    type.addField("Phone");
	    type.addField("State");
	    type.addField("Zip");

		// use a http proxy to get the data
	    RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, "data.xml");
	    HttpProxy proxy = new HttpProxy(builder);

	    // need a loader, proxy, and reader
	    XmlReader reader = new XmlReader(type);
		 
 		final BaseListLoader loader = new BaseListLoader(proxy, reader);
	    final ListStore<ModelData> store = new ListStore<ModelData>(loader);

	    loader.addLoadListener(new LoadListener(){
	    	 public void loaderBeforeLoad(LoadEvent le) {
	    	 }
	    	 public void loaderLoad(LoadEvent le) {

	    		 ModelDataProxy sdp = (ModelDataProxy)getFacade().retrieveProxy(ModelDataProxy.NAME);
	    		 sdp.storeData(store.getModels());
	    	 }
	    	 public void loaderLoadException(LoadEvent le) {
	    	 }
			});
	    
	    loader.load();

	}
}
